package pers.karl.util;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * WEB文件工具类
 */
public class WebFileUtil {

    /**
     * 导出文件
     * @param inputStream 输入流
     * @param fileName 文件名，带有扩展名
     * @return ResponseEntity 响应信息消息体
     * @throws IOException
     */
    public static ResponseEntity export(InputStream inputStream, String fileName) throws IOException {

        if(inputStream == null){
            throw new IllegalArgumentException("inputStream is null");
        }
        if(StringUtils.isEmpty(fileName)){
            throw new IllegalArgumentException("fileName is empty");
        }

        // set file name
        fileName =  new String(fileName.getBytes("UTF-8"),"iso-8859-1");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte[] bytes = new byte[1024];

        int len;
        while((len = inputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
        }
        inputStream.close();

        bytes = outputStream.toByteArray();
        outputStream.close();

        return new ResponseEntity<>(bytes,headers, HttpStatus.CREATED);
    }

    /**
     * 获取提交的文件
     * @param request
     * @param fileName 文件名
     * @return
     * @throws IOException
     */
    public static File getUploadFile(HttpServletRequest request, String fileName) throws IOException {
        // 检查所需数据
        List<MultipartFile> multipartFiles =((MultipartHttpServletRequest)request).getFiles(fileName);
        if(multipartFiles.isEmpty()){
            throw new IllegalArgumentException("the name of file : " + fileName + " is null");
        }
        MultipartFile multipartFile = multipartFiles.get(0);

        // 保存上传的文件
        String fileParentPath = request.getServletContext().getRealPath("") + "/temp";
        System.out.println(fileParentPath);
        File directory = new File(fileParentPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(directory, RandomStringUtils.random(20,"123456789abcdefghijklmnopqrstuvwxyz"));
        if (file.exists()) {
            file.delete();
        }
        multipartFile.transferTo(file);
        return file;
    }

}
